//
//  TestViewController.m
//  视频播放
//
//  Created by zhangzhenyun on 2018/7/21.
//  Copyright © 2018年 Beijing Youjiu Network. All rights reserved.
//

#import "TestViewController.h"
#import "AudioPlayView.h"
#import <AVFoundation/AVFoundation.h>
#import "ISEParams.h"
#import "TimeLabel.h"
#import "ISEResultXmlParser.h"
#import "PopupView.h"
#import "XMLReader.h"
#import "LoadingHUD.h"
#import "SpectrumView.h"
#import "RecordPlayView.h"
#import "LineView.h"

@interface TestViewController ()<IFlySpeechEvaluatorDelegate,AVAudioPlayerDelegate>//, ISEResultXmlParserDelegate>

@property (nonatomic, strong) UIButton *recordBtn;

@property (nonatomic, strong) AudioPlayView *audioView;

@property (nonatomic, strong) RecordPlayView *recordView;

@property (nonatomic, strong) AVAudioPlayer *audioPlay;

@property (nonatomic, strong) NSString *recoderName;

@property (nonatomic, strong) NSURL *recordedFile;
/** 语音评测对象 */
@property (nonatomic, strong) IFlySpeechEvaluator *iFlySpeechEvaluator;
/** 参数 */
@property (nonatomic, strong) ISEParams *iseParams;

@property (nonatomic, strong) TimeLabel *timeLabel;

@property (nonatomic, strong) PopupView *popupView;

@property (nonatomic, strong) UILabel *totalScore;

@property (nonatomic, strong) NSString *score;

@property (nonatomic, strong) AVAudioRecorder *recorder;

@property (nonatomic, strong) NSDictionary *recordSetting;

@property (nonatomic, strong) SpectrumView *spectrumView;

@property (nonatomic, assign) BOOL isAnimating;

@property (nonatomic, strong) LineView *lineView;


@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
    [self layout];
    _isAnimating = NO;
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.score = @"";
    self.navigationController.navigationBar.hidden = YES;
}
- (void)setupViews {
    self.view.backgroundColor = UIColorFromRGB(0xD53E4A);
    [self.view addSubview:self.recordBtn];
    [self.view addSubview:self.audioView];
//    [self.view addSubview:self.spectrumView];
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.recordView];
    [self.view addSubview:self.totalScore];
    [self.view addSubview:self.timeLabel];
}
#pragma mark - event
- (void)playOrPauseClick:(UIButton *)btn{
   
    [self playKeyAnimation];
    [self.recordView hideRecordView];
    self.isAnimating = NO;
    if (btn.selected) {
        [LoadingHUD showIn:self.view];
         [self.recordBtn setBackgroundImage:[UIImage imageNamed:@"Group"] forState:UIControlStateSelected];
         [self endRecording];
    } else {
        [self.recordBtn setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateSelected];
        [self startRecording];
        [self.lineView removeFromSuperview];
        self.lineView = nil;
        [self.view addSubview:self.lineView];
    }
}

- (void)starButtonClicked:(id)sender
{
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(playOrPauseClick:) object:sender];
    [self performSelector:@selector(playOrPauseClick:) withObject:sender afterDelay:0.1];
}

- (void)startRecording {
    [self startListening];
    [self.spectrumView start];
    if (self.totalScore) {
        [self hideScoreLabel];
    }
    [self.timeLabel timeStart];
    self.recordBtn.selected = YES;
}
- (void)endRecording {
    [self move];
    [self stopListening];
    [self.timeLabel timerStop];
    [self.spectrumView stop];
    self.recordBtn.selected = NO;
    
}

- (void)move {
    if (self.isAnimating) {
        return;
    }
    self.recordView = nil;
    [self.view addSubview:self.recordView];
    self.isAnimating = YES;
    [self.recordView showRecordView];
}
- (void)handleScore{
 
    NSString *string = [NSString stringWithFormat:@"%@分",self.score];
    NSRange range = [string rangeOfString:@"分"];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:string];
    [attr setAttributes:@{NSFontAttributeName:RMFont(18)} range:range];
    self.totalScore.attributedText = attr;
    [self showScoreLabel];
}

- (void)showScoreLabel{
    CGFloat kAnimationDuration = 1.0f;
    CAGradientLayer *contentLayer = (CAGradientLayer *)self.totalScore.layer;
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    scaleAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0, 0, 1)];
    scaleAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
    scaleAnimation.duration = kAnimationDuration;
    scaleAnimation.cumulative = NO;
    scaleAnimation.repeatCount = 1;
    [scaleAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [contentLayer addAnimation: scaleAnimation forKey:@"myScale"];
    
    CABasicAnimation *showViewAnn = [CABasicAnimation animationWithKeyPath:@"opacity"];
    showViewAnn.fromValue = [NSNumber numberWithFloat:0.0];
    showViewAnn.toValue = [NSNumber numberWithFloat:1.0];
    showViewAnn.duration = kAnimationDuration;
    showViewAnn.fillMode = kCAFillModeForwards;
    showViewAnn.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    showViewAnn.removedOnCompletion = NO;
    [contentLayer addAnimation:showViewAnn forKey:@"myShow"];
    
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.duration = kAnimationDuration;
    group.removedOnCompletion = NO;
    group.repeatCount = 1;
    group.fillMode = kCAFillModeForwards;
    [group setAnimations:@[scaleAnimation,showViewAnn]];
    
    [contentLayer addAnimation:group forKey:@"animationOpacity"];
}

- (void)hideScoreLabel{
    CGFloat kAnimationDuration = 1.0f;
    CAGradientLayer *contentLayer = (CAGradientLayer *)self.totalScore.layer;
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    scaleAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0, 0, 1)];
    scaleAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
    scaleAnimation.duration = kAnimationDuration;
    scaleAnimation.cumulative = NO;
    scaleAnimation.repeatCount = 1;
    [scaleAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [contentLayer addAnimation: scaleAnimation forKey:@"myScale"];
    
    CABasicAnimation *showViewAnn = [CABasicAnimation animationWithKeyPath:@"opacity"];
    showViewAnn.fromValue = [NSNumber numberWithFloat:1.0];
    showViewAnn.toValue = [NSNumber numberWithFloat:0.0];
    showViewAnn.duration = kAnimationDuration;
    showViewAnn.fillMode = kCAFillModeForwards;
    showViewAnn.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    showViewAnn.removedOnCompletion = NO;
    [contentLayer addAnimation:showViewAnn forKey:@"myShow"];
    
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.duration = kAnimationDuration;
    group.removedOnCompletion = NO;
    group.repeatCount = 1;
    group.fillMode = kCAFillModeForwards;
    [group setAnimations:@[scaleAnimation,showViewAnn]];
    
    [contentLayer addAnimation:group forKey:@"animationOpacity"];
}


#pragma mark - 讯飞语音
- (void)startListening {
    NSString *voiceStr = @"happy birthday to you";
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSMutableData *buffer = [NSMutableData dataWithData:[voiceStr dataUsingEncoding:encoding]];
    NSLog(@" \nen buffer length: %lu",(unsigned long)[buffer length]);
    // 开始评测
    BOOL ret = [self.iFlySpeechEvaluator startListening:buffer params:nil];
    if(ret){
        [self obtainAudioFilePath];
        dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(globalQueue, ^{
             [self startRecord];
        });
    }
}

- (void)stopListening {
    [self.iFlySpeechEvaluator stopListening];
}

#pragma mark - 本地语音播放
- (void)playMyAudio{
    NSString *soundPath = [[NSBundle mainBundle]pathForResource:@"tts" ofType:@"mp3"];
    NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
    //初始化播放器对象
    self.audioPlay = [[AVAudioPlayer alloc]initWithContentsOfURL:soundUrl error:nil];
    //设置声音的大小
    self.audioPlay.volume = 0.8;//范围为（0到1）；
    //设置循环次数，如果为负数，就是无限循环
    self.audioPlay.numberOfLoops = 1;
    //设置播放进度
    self.audioPlay.currentTime = 0;
    self.audioPlay.delegate = self;
    //准备播放
    [self.audioPlay prepareToPlay];
    [self.audioPlay play];
    self.audioView.isPlay = YES;
}

- (NSURL *)obtainAudioFilePath{
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = [dirPaths objectAtIndex:0];
    NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"recordTest.caf"];
    NSURL *url = [NSURL fileURLWithPath:soundFilePath];
    self.recordedFile = url;
    return self.recordedFile;
}

- (void)startRecord{
    NSError *error = nil;
    NSURL *wavUrl = self.recordedFile;
    // 在实例化AVAudioRecorder之前，先开启会话,否则真机上录制失败
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *setCategoryError = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
    if(setCategoryError){
        NSLog(@"%@", [setCategoryError description]);
    }
    self.recorder = [[AVAudioRecorder alloc] initWithURL:wavUrl settings:self.recordSetting error:&error];
    if ([self.recorder prepareToRecord] == YES){
        self.recorder.meteringEnabled = YES;
        [self.recorder record];
    }else {
        NSLog(@"FlyElephant--初始化录音失败");
    }
    if (!self.recorder || error) {
        self.recorder = nil;
        return;
    }
}

- (void)playMyRecordAudio{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;  // 加上这两句，否则声音会很小
    [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
    self.audioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:_recordedFile error:nil];
    self.audioPlay.numberOfLoops = 0;
    [self.audioPlay prepareToPlay];
    self.audioPlay.delegate = self;
    [self.audioPlay play];
    self.recordView.isPlay = YES;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"audioEnd" object:nil];
}


- (float)getAudioTimeWithType:(NSInteger)type{
    NSString *soundPath;
    NSURL *fileURL;
    if (type == 1) {
        soundPath  = [[NSBundle mainBundle]pathForResource:@"tts" ofType:@"mp3"];
        fileURL = [NSURL fileURLWithPath:soundPath];
    }else{
        fileURL = self.recordedFile;
    }
    AVURLAsset*audioAsset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
    CMTime audioDuration = audioAsset.duration;
    float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
    NSLog(@"%f",audioDurationSeconds);
    return audioDurationSeconds;
}

#pragma mark - IFlySpeechEvaluatorDelegate
// 音量和数据回调
- (void)onVolumeChanged:(int)volume buffer:(NSData *)buffer{
    [self.popupView setText:[NSString stringWithFormat:@"%@：%d", NSLocalizedString(@"T_RecVol", nil),volume]];
//    [self.view addSubview:self.popupView];
    [self.recorder updateMeters];
    //取得第一个通道的音频，音频强度范围是-160到0
    float power= [self.recorder averagePowerForChannel:0];
    self.lineView.volum = volume;
}
// 开始录音回调
- (void)onBeginOfSpeech{}
// 停止录音回调
- (void)onEndOfSpeech{
    [self endRecording];
}
// 会话取消回调
- (void)onCancel{}
// 评测错误回调
- (void)onCompleted:(IFlySpeechError *)errorCode{
    if(errorCode && errorCode.errorCode!=0){
        [self.popupView setText:[NSString stringWithFormat:@"Error：%d %@",[errorCode errorCode],[errorCode errorDesc]]];
//        [self.view addSubview:self.popupView];
          NSLog(@"评测错误回调");
         [self endRecording];
        [LoadingHUD hideIn:self.view];
        
    }
}
/** 评测结果回调 */
- (void)onResults:(NSData *)results isLast:(BOOL)isLast{
    [LoadingHUD hideIn:self.view];
    self.recordBtn.selected = !self.recordBtn.selected;
    if (results) {
        NSString *showText = @"";
        const char *chResult=[results bytes];
        BOOL isUTF8 = [[self.iFlySpeechEvaluator parameterForKey:[IFlySpeechConstant RESULT_ENCODING]]isEqualToString:@"utf-8"];
        NSString *strResults=nil;
        if (isUTF8) {
            strResults=[[NSString alloc] initWithBytes:chResult length:[results length] encoding:NSUTF8StringEncoding];
        } else {
            NSLog(@"result encoding: gb2312");
            NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            strResults=[[NSString alloc] initWithBytes:chResult length:[results length] encoding:encoding];
        }
        if (strResults) {
            showText = [showText stringByAppendingString:strResults];
        }
        //        self.score = showText;
        if (isLast){
            [self.popupView setText: NSLocalizedString(@"T_ISE_End", nil)];
//            [self.view addSubview:self.popupView];
            
            NSString *totalScore = [self totalScoreFromXMLString:strResults];
            totalScore = [NSString stringWithFormat:@"%.f",totalScore.floatValue];
            NSLog(@"%@",totalScore);
            self.score = totalScore;
            //评测成功
            [self handleScore];
            _recordView.time = [self getAudioTimeWithType:2];
             [self endRecording];
        }
    } else {
        if (isLast) {
            [self.popupView setText: NSLocalizedString(@"M_ISE_Msg", nil)];
//            [self.view addSubview:self.popupView];
             [self endRecording];
        }
    }
}

- (NSString *)totalScoreFromXMLString:(NSString *)xmlString {
    NSError *error;
    NSDictionary *dic = [XMLReader dictionaryForXMLString:xmlString error:&error];
    if (error) {
        return 0;
    }
    NSDictionary *xmlResutlDic =  dic[@"xml_result"];
    NSDictionary *readSentenceDic = xmlResutlDic[@"read_sentence"];
    NSDictionary *recPaperDic = readSentenceDic[@"rec_paper"];
    NSDictionary *readChapterDic = recPaperDic[@"read_chapter"];
    NSDictionary *sentenceDic = readChapterDic[@"sentence"];
    NSString *totalScore = sentenceDic[@"total_score"];
    totalScore = [NSString stringWithFormat:@"%.f",(totalScore.floatValue - 2.5) * 40.0];
    totalScore = [NSString stringWithFormat:@"%f",totalScore.floatValue < 0 ? 0 : totalScore.floatValue];
    
    return totalScore;
}
#pragma mark - IFlyPcmRecorderDelegate
- (void) onIFlyRecorderBuffer: (const void *)buffer bufferSize:(int)size {
    NSData *audioBuffer = [NSData dataWithBytes:buffer length:size];
    int ret = [self.iFlySpeechEvaluator writeAudio:audioBuffer];
    if (!ret) {
        [self.iFlySpeechEvaluator stopListening];
    }
}

- (void)onIFlyRecorderError:(IFlyPcmRecorder*)recoder theError:(int) error {}
//range from 0 to 30
- (void) onIFlyRecorderVolumeChanged:(int) power {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.popupView setText:[NSString stringWithFormat:@"%@：%d", NSLocalizedString(@"T_RecVol", nil),power]];
//        [self.view addSubview:self.popupView];
    
    });
}

#pragma mark - layout
- (void)layout{
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Fix375(123));
        make.top.mas_equalTo(Fix375(100));
        make.size.mas_equalTo(CGSizeMake(Fix375(129), Fix375(28)));
    }];
    
    [self.recordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Fix375(155));
        make.bottom.mas_equalTo(-Fix375(180));
        make.size.mas_equalTo(CGSizeMake(Fix375(66), Fix375(66)));
    }];
    
    [self.audioView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Fix375(20));
        make.right.mas_equalTo(-Fix375(20));
        make.bottom.mas_equalTo(-Fix375(17));
        make.height.mas_equalTo(Fix375(50));
    }];
    
    [self.totalScore mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(Fix375(250));
    }];
}

#pragma mark - getter
-(UIButton *)recordBtn {
    if (_recordBtn == nil) {
        _recordBtn = [[UIButton alloc]init];
        _recordBtn.titleLabel.font = RMFont(12);
        [_recordBtn setTitleColor:UIColorFromRGB(0xFFFFFF) forState:UIControlStateNormal];
        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"Group"] forState:UIControlStateNormal];
//        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateSelected];
        [_recordBtn addTarget:self action:@selector(starButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _recordBtn;
}

- (void)playKeyAnimation
{
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    keyAnimation.duration = 0.1;
    keyAnimation.values = @[@0.9,@1.1,@1.0];
    keyAnimation.calculationMode = kCAAnimationCubicPaced;
    [self.recordBtn.layer addAnimation:keyAnimation forKey:@"keyAnimation"];

}
- (void)stopRecordBtnAnimation {
    
}
- (AudioPlayView *)audioView{
    if (!_audioView) {
        _audioView = [[AudioPlayView alloc]init];
        _audioView.layer.cornerRadius = 5;
        _audioView.layer.masksToBounds = YES;
        _audioView.titleString = @"Happy Birthday To You";
        _audioView.time = [self getAudioTimeWithType:1];
        [_audioView.playBtn setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
        [_audioView.playBtn setImage:[UIImage imageNamed:@"stopRecord"] forState:UIControlStateSelected];
        __weak TestViewController *vc = self;
        __weak AudioPlayView *weakSelf = _audioView;
        _audioView.clickAudioBlock = ^(BOOL select) {
            if (select) {
                [vc playMyAudio];
            }else{
                if ([vc.audioPlay isPlaying]) {
                    [vc.audioPlay pause];
                    weakSelf.isPlay = NO;
                }
            }
        };
    }
    return _audioView;
}
- (RecordPlayView *)recordView{
    if (!_recordView) {
        _recordView = [[RecordPlayView alloc]init];
        _recordView.frame = CGRectMake(Fix375(20), Fix375(420), SCREEN_WIDTH - Fix375(40), Fix375(50));
        _recordView.alpha = 0.f;
        [_recordView.playBtn setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
        [_recordView.playBtn setImage:[UIImage imageNamed:@"stopRecord"] forState:UIControlStateSelected];
        _recordView.transform = CGAffineTransformMakeScale(0.f, 0.f);
        _recordView.layer.cornerRadius = 5;
        _recordView.layer.masksToBounds = YES;
        _recordView.titleString = @"我的音频";
        __weak TestViewController *vc = self;
        __weak RecordPlayView *weakSelf = _recordView;
        _recordView.clickRecordBlock = ^(BOOL select) {
            if (select) {
                [vc playMyRecordAudio];
            }else{
                if ([vc.audioPlay isPlaying]) {
                    [vc.audioPlay pause];
                    weakSelf.isPlay = NO;
                }
            }
        };
    }
    return _recordView;
}
- (PopupView *)popupView {
    if (!_popupView) {
        _popupView = [[PopupView alloc]initWithFrame:CGRectMake(Fix375(100), Fix375(300), 0, 0)];
        _popupView.ParentView = self.view;
    }
    return _popupView;
}

- (IFlySpeechEvaluator *)iFlySpeechEvaluator {
    if (!_iFlySpeechEvaluator) {
        _iFlySpeechEvaluator = [IFlySpeechEvaluator sharedInstance];
        _iFlySpeechEvaluator.delegate = self;
        // 设置训练参数
        // 清空参数
        [_iFlySpeechEvaluator setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        // 设置评测采样率
        [_iFlySpeechEvaluator setParameter:@"16000" forKey:[IFlySpeechConstant SAMPLE_RATE]];
        // 设置评测题目编码，如果是utf-8格式，请添加bom头，添加方式可参考demo。
        [_iFlySpeechEvaluator setParameter:@"utf-8" forKey:[IFlySpeechConstant TEXT_ENCODING]];
        // 设置评测题目结果格式，目前仅支持xml
        [_iFlySpeechEvaluator setParameter:@"xml" forKey:[IFlySpeechConstant ISE_RESULT_TYPE]];
        // 评测录音保存路径
        [self.iFlySpeechEvaluator setParameter:@"eva.pcm" forKey:[IFlySpeechConstant ISE_AUDIO_PATH]];
        // 设置评测前端点超时
        [_iFlySpeechEvaluator setParameter:self.iseParams.bos forKey:[IFlySpeechConstant VAD_BOS]];
        // 设置评测后端点超时
        [_iFlySpeechEvaluator setParameter:self.iseParams.eos forKey:[IFlySpeechConstant VAD_EOS]];
        // 设置评测题型
        [_iFlySpeechEvaluator setParameter:self.iseParams.category forKey:[IFlySpeechConstant ISE_CATEGORY]];
        // 设置评测语言
        [_iFlySpeechEvaluator setParameter:self.iseParams.language forKey:[IFlySpeechConstant LANGUAGE]];
        // 设置评测结果级别
        [_iFlySpeechEvaluator setParameter:self.iseParams.rstLevel forKey:[IFlySpeechConstant ISE_RESULT_LEVEL]];
        // 设置评测超时
        [_iFlySpeechEvaluator setParameter:self.iseParams.timeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
    }
    
    return _iFlySpeechEvaluator;
}

- (ISEParams *)iseParams {
    if (!_iseParams) {
        _iseParams = [ISEParams fromUserDefaults];
    }
    return _iseParams;
}

- (TimeLabel *)timeLabel{
    if (!_timeLabel) {
        _timeLabel = [[TimeLabel alloc]init];
        _timeLabel.textColor = UIColorFromRGB(0xFFFFFF);
        _timeLabel.font = [UIFont boldSystemFontOfSize:28];
        _timeLabel.minute = 03;
        _timeLabel.second = 00;
    }
    return _timeLabel;
}

- (UILabel *)totalScore{
    if (!_totalScore) {
        _totalScore = [[UILabel alloc]init];
        _totalScore.textColor = UIColorFromRGB(0xFFFFFF);
        _totalScore.font = [UIFont boldSystemFontOfSize:48];
        _totalScore.alpha = 0;
    }
    return _totalScore;
}

-(LineView *)lineView {
    if (_lineView == nil) {
        _lineView = [[LineView alloc] initWithFrame:CGRectMake(0, Fix375(140), SCREEN_WIDTH, Fix375(90))];
    }
    return _lineView;
}

- (SpectrumView *)spectrumView{
    if (!_spectrumView) {
        _spectrumView = [[SpectrumView alloc]initWithFrame:CGRectMake(0, Fix375(140), SCREEN_WIDTH, Fix375(89))];
        _spectrumView.middleInterval = 120;
        __weak TestViewController *weakSelf = self;
        __weak SpectrumView * weakSpectrum = self.spectrumView;
        _spectrumView.itemLevelCallback = ^() {
            if (!weakSelf.recordBtn.selected) {
                return;
            }
            [weakSelf.recorder updateMeters];
            //取得第一个通道的音频，音频强度范围是-160到0
            float power= [weakSelf.recorder averagePowerForChannel:0];
            weakSpectrum.level = power;
        };
    }
    return _spectrumView;
}


-(NSDictionary *)recordSetting{
    
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    
    //设置录音格式
    
    [dicM setObject:@(kAudioFormatLinearPCM)forKey:AVFormatIDKey];
    
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    
    [dicM setObject:@(8000)forKey:AVSampleRateKey];
    
    //设置通道,这里采用单声道
    
    [dicM setObject:@(1)forKey:AVNumberOfChannelsKey];
    
    //每个采样点位数,分为8、16、24、32
    
    [dicM setObject:@(16)forKey:AVLinearPCMBitDepthKey];
    
    //是否使用浮点数采样
    
    [dicM setObject:@(YES)forKey:AVLinearPCMIsFloatKey];
    
    //....其他设置等
    
    return dicM;
    
}

@end
